package com.mall.user.services;

import com.alibaba.fastjson.JSON;
import com.mall.commons.tool.exception.ValidateException;
import com.mall.user.IRegisterService;
import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.entitys.UserVerify;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dal.persistence.UserVerifyMapper;
import com.mall.user.dto.UserRegisterRequest;
import com.mall.user.dto.UserRegisterResponse;
import com.mall.user.dto.UserVerifyRequest;
import com.mall.user.dto.UserVerifyResponse;
import com.mall.user.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * @description：
 * @author： Yj
 * @create： 2022/01/20
 **/

@Service
@Slf4j
@Anoymous
public class RegisterServiceImpl implements IRegisterService {

    @Autowired
    MemberMapper memberMapper;

    @Autowired
    UserVerifyMapper userVerifyMapper;

    @Autowired
    JavaMailSender mailSender;

    @Override
    public UserRegisterResponse register(UserRegisterRequest registerRequest) {
        UserRegisterResponse response = new UserRegisterResponse();
        try {
            //判空验证
            registerRequest.requestCheck();
            //验证用户名是否重复
            volidUserNameRepeat(registerRequest);
            //1.用户表插入一条记录
            Member member = new Member();
            member.setUsername(registerRequest.getUserName());
            member.setEmail(registerRequest.getEmail());
            //密码要进行加密处理
            String userPwd = DigestUtils.md5DigestAsHex(registerRequest.getUserPwd().getBytes());
            member.setPassword(userPwd);
            //设置插入默认值
            member.setCreated(new Date());
            member.setUpdated(new Date());
            //初始未激活
            member.setIsVerified("N");
            member.setState(1);
            int effectRows = memberMapper.insert(member);
            if (effectRows != 1){
                response.setCode(SysRetCodeConstants.USER_REGISTER_FAILED.getCode());
                response.setMsg(SysRetCodeConstants.USER_REGISTER_FAILED.getMessage());
                return response;
            }
            //2.用户验证表插入一条记录
            UserVerify userVerify = new UserVerify();
            userVerify.setUsername(registerRequest.getUserName());
            userVerify.setIsExpire("N");
            userVerify.setIsVerify("N");
            String key = member.getUsername() + member.getPassword();
            String uuid = DigestUtils.md5DigestAsHex(key.getBytes());
            userVerify.setUuid(uuid);
            //设置默认值
            userVerify.setRegisterDate(new Date());
            int rows = userVerifyMapper.insert(userVerify);
            if (rows != 1){
                response.setCode(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getCode());
                response.setMsg(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getMessage());
                return response;
            }
            //3.发送用户激活邮件
            // 发送用户激活邮件
            sendMail(uuid,registerRequest);

            //打印日志
            log.info("用户注册成功，注册参数request:{}", JSON.toJSONString(registerRequest));
            //注册成功
            response.setCode(SysRetCodeConstants.SUCCESS.getCode());
            response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        } catch (Exception e) {
            log.error("RegisterServiceImpl.register Occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }
        return response;
    }
/**
 * @description: 激活账户
 * @param:
 * @return:
 * @author 亓永杰
 * @date: 2022-01-21 15:07
 */
    @Override
    public UserVerifyResponse verify(UserVerifyRequest request) {
        String userName = request.getUserName();
        String uuid = request.getUuid();
        UserVerifyResponse response = new UserVerifyResponse();
        UserVerify userVerify = new UserVerify();

        userVerify.setIsVerify("Y");
        userVerify.setIsExpire("Y");
        Example verifyExample = new Example(UserVerify.class);
        verifyExample.createCriteria().andEqualTo("uuid",uuid);
        int effectRows = userVerifyMapper.updateByExampleSelective(userVerify, verifyExample);
        if (effectRows != 1){
            response.setCode(SysRetCodeConstants.USER_REGISTER_FAILED.getCode());
            response.setMsg(SysRetCodeConstants.USER_REGISTER_FAILED.getMessage());
            return response;
        }
        Example memberExample = new Example(Member.class);
        memberExample.createCriteria().andEqualTo("username",userName);
        Member member = new Member();
        member.setIsVerified("Y");
        int effectRows1 = memberMapper.updateByExampleSelective(member, memberExample);
        if (effectRows1 != 1){
            response.setCode(SysRetCodeConstants.USER_REGISTER_FAILED.getCode());
            response.setMsg(SysRetCodeConstants.USER_REGISTER_FAILED.getMessage());
            return response;
        }
        response.setCode(SysRetCodeConstants.SUCCESS.getCode());
        response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        return response;
    }

    /**
 * @description: 发送用户激活邮件
 * @param:
 * @return:
 * @author 亓永杰
 * @date: 2022-01-20 18:58
 */
    private void sendMail(String uuid, UserRegisterRequest registerRequest) {
        SimpleMailMessage message = new SimpleMailMessage();
//        发送邮件的标题和发件人
        message.setFrom("1106740296@qq.com");
        message.setSubject("CSMALL用户激活");
        message.setTo(registerRequest.getEmail());
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("http://localhost:9999/user/verify?uuid=").append(uuid).append("&userName=").append(registerRequest.getUserName());
        message.setText(stringBuilder.toString());
        mailSender.send(message);
    }

    //验证用户名是否重复
    private void volidUserNameRepeat(UserRegisterRequest registerRequest) {
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username",registerRequest.getUserName());
        List<Member> memberList = memberMapper.selectByExample(example);
        //判空和判断是否为null（使用list.isEmpty可能出现空指针异常）
        if (!CollectionUtils.isEmpty(memberList)){
            throw new ValidateException(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getCode(), SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getMessage());
        }
    }
}
